#!/bin/sh

check_user_on_primary() {
  check_user "$CLUSTER_NAME" 1
}

check_user_on_replica() {
  check_user "$CLUSTER_NAME-replicas" 0
}

check_user_on_sharded_primary() {
  local HOST="${1:-$CLUSTER_NAME}"
  local CLUSTER_NAME="${2:-$CLUSTER_NAME-coord}"
  local FROM_HOST_INDEX="${3:-1}"
  check_user "$HOST" "$FROM_HOST_INDEX"
}

check_user() {
  local HOST="$1"
  local FROM_HOST_INDEX="$2"
  local DATABASE="${DATABASE:-postgres}"
  wait_until eval 'run_query -p 5432 -i "$FROM_HOST_INDEX" -h "$HOST" -c "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" \
    -q "SELECT usename FROM pg_catalog.pg_user;" -d "$DATABASE" | grep -q "^sakila$"'
  if run_query -p 5432 -i "$FROM_HOST_INDEX" -h "$HOST" -c "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -q "SELECT usename FROM pg_catalog.pg_user;" -d "$DATABASE" \
    | grep -q "^sakila$"
  then
    success "sakila user was created successfully"
  else
    fail "sakila user was not created"
  fi
}

check_database_on_primary() {
  check_database "$CLUSTER_NAME" 1
}

check_database_on_replica() {
  check_database "$CLUSTER_NAME-replicas" 0
}

check_database_on_sharded_primary() {
  local HOST="${1:-$CLUSTER_NAME}"
  local CLUSTER_NAME="${2:-$CLUSTER_NAME-coord}"
  local FROM_HOST_INDEX="${3:-1}"
  check_database "$HOST" "$FROM_HOST_INDEX"
}

check_database() {
  local HOST="$1"
  local FROM_HOST_INDEX="$2"
  local DATABASE="${DATABASE:-sakila}"
  if run_query -p 5432 -i "$FROM_HOST_INDEX" -h "$HOST" -c "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -q "SELECT datname FROM pg_catalog.pg_database;" -d "$DATABASE" \
    | grep -q "^$DATABASE$"
  then
    success "sakila database was created successfully"
  else
    fail "sakila database was not created"
  fi
}

check_schema_on_primary() {
  check_schema "$CLUSTER_NAME" 1
}

check_schema_on_replica() {
  check_schema "$CLUSTER_NAME-replicas" 0
}

check_schema_on_sharded_primary() {
  local HOST="${1:-$CLUSTER_NAME}"
  local CLUSTER_NAME="${2:-$CLUSTER_NAME-coord}"
  local FROM_HOST_INDEX="${3:-1}"
  check_schema "$HOST" "$FROM_HOST_INDEX"
}

check_schema() {
  local HOST="$1"
  local FROM_HOST_INDEX="$2"
  local DATABASE="${DATABASE:-sakila}"
  if run_query -p 5432 -i "$FROM_HOST_INDEX" -h "$HOST" -c "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -q "SELECT tablename FROM pg_catalog.pg_tables;" -d "$DATABASE" \
    | grep -q "^film$" \
    && run_query -p 5432 -i "$FROM_HOST_INDEX" -h "$HOST" -c "$CLUSTER_NAME" -n "$CLUSTER_NAMESPACE" -q "SELECT tablename FROM pg_catalog.pg_tables;" -d "$DATABASE" \
    | grep -q "^store$"
  then
    success "sakila schema was created successfully"
  else
    fail "sakila schema was not created"
  fi
}
